package com.salton123.ui.base

import android.annotation.SuppressLint
import android.app.Activity
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity

/**
 * @Time:2021/4/20 17:00
 * @Author:wujinsheng
 * @Description:
 */
open class LifeDelegateImpl : ILifeDelegate {
    private lateinit var mHost: ILifeDelegate

    override fun attach(impl: ILifeDelegate) {
        this.mHost = impl
    }

    override fun show(vararg views: View) {
        for (view in views) {
            view.visibility = View.VISIBLE
        }
    }

    override fun hide(vararg views: View) {
        for (view in views) {
            view.visibility = View.GONE
        }
    }

    override fun self(): ILifeDelegate {
        return this
    }

    override fun longToast(toast: String?) {
        if (activity() != null) {
            Toast.makeText(activity(), toast, Toast.LENGTH_LONG).show()
        }
    }

    override fun shortToast(toast: String?) {
        if (activity() != null) {
            Toast.makeText(activity(), toast, Toast.LENGTH_SHORT).show()
        }
    }

    override fun activity(): FragmentActivity? {
        var mHostActivity: FragmentActivity?
        if (self() is Fragment) {
            mHostActivity = (self() as Fragment).activity
        } else if (self() is Activity) {
            mHostActivity = self() as FragmentActivity
        } else {
            throw RuntimeException("instance must Fragment or Activity")
        }
        return mHostActivity
    }

    @SuppressLint("UseRequireInsteadOfGet")
    override fun <T : View?> f(resId: Int): T {
        val current = mHost
        if (current is Activity) {
            return current.findViewById<T>(resId)
        } else if (current is Fragment) {
            return current.view?.findViewById<T>(resId)!!
        }
        return null as T
    }

    override fun onClick(v: View?) {
        self().onClick(v)
    }

    override fun setListener(vararg ids: Int) {
        for (id in ids) {
            f<View>(id).setOnClickListener(this)
        }
    }

    override fun setListener(vararg views: View) {
        for (view in views) {
            view.setOnClickListener(this)
        }
    }
}